/*
* Author: zhfayuan Create at 2021/8/31.
* Email:afst2012@outlook.com
* Copyright：
* Desc：
* Version:
* History：
*/


#include <iostream>
#include<string.h>
#include "AudioResampler.h"

AudioResampler::AudioResampler()
:_st(nullptr),_initialize(false)
{

}
AudioResampler::~AudioResampler()
{
    if(_st){
        speex_resampler_destroy(_st);
        _st = nullptr;
    }
}

void AudioResampler::initialize(int32_t in_rate, int32_t out_rate, int32_t channel)
{
    int err;
    if(_initialize)
        return;
    if(channel != 1 && channel != 2)
        return;
    _out_channel = 2;
    _out_rate = out_rate;
    _in_channel = channel;
    _st = speex_resampler_init(_out_channel, in_rate, out_rate, 10, &err);
    _initialize = _st ? true : false;
}

void AudioResampler::resample(std::shared_ptr<std::vector<char>> &in,std::function<void(std::shared_ptr<std::vector<char>> &,int32_t ,int32_t )> func)
{
    int byte,ret;
    spx_uint32_t in_len,out_len;

    if(!_initialize || nullptr == _st || nullptr == func)
        return;

    if(_in_channel == 1){
        spx_int16_t *src,*dst;
        dst = (spx_int16_t*)_in_pcm;
        src = (spx_int16_t*)in->data();
        in_len =  in->size() / sizeof(spx_int16_t);
        for (size_t i = 0; i < in_len ; i++)
        {
            *dst = *src;dst++;
            *dst = *src;dst++;src++;
        }
        byte = (in_len * sizeof(spx_int16_t))<< 1;
    } else {
        byte = in->size();
        memcpy(_in_pcm,in->data(),in->size());
    }

    {
        in_len = byte >> 2; //byte * 8/(channel *bit)
        out_len = sizeof(_out_pcm);
        ret = speex_resampler_process_interleaved_int(_st, (spx_int16_t*)_in_pcm, &in_len, (spx_int16_t*)_out_pcm, &out_len);
        if (ret == RESAMPLER_ERR_SUCCESS){
            auto out = std::make_shared<std::vector<char>>();
            out->assign(_out_pcm,_out_pcm + (out_len<<2));
            func(out,_out_rate,_out_channel);
        }
    }

}